﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace CodeContrib
{
	public static class DrawingExtensions
	{
		public static GraphicsPath Deform(this GraphicsPath graphicsPath, int height, int width, int warpFactor)
		{
			double xAmplitude = warpFactor * width / 100;
			double yAmplitude = warpFactor * height / 85;
			var xFrequency = 2 * Math.PI / width;
			var yFrequency = 2 * Math.PI / height;

			var deformed = new PointF[graphicsPath.PathPoints.Length];

			var randomdouble = new RandomDouble();

			var xSeed = randomdouble.Next() * 2 * Math.PI;
			var ySeed = randomdouble.Next() * 2 * Math.PI;

			for (var i = 0; i < graphicsPath.PathPoints.Length; i++)
			{
				var original = graphicsPath.PathPoints[i];
				var value = xFrequency * original.X + yFrequency * original.Y;

				var xOffset = (int)(xAmplitude * Math.Sin(value + xSeed));
				var yOffset = (int)(yAmplitude * Math.Sin(value + ySeed));

				deformed[i] = new PointF(original.X + xOffset, original.Y + yOffset);
			}

			return new GraphicsPath(deformed, graphicsPath.PathTypes);
		}
	}
}